import { ref, onMounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { FormInstance } from "element-plus";
import { message } from "@/utils/message";
import { getSysXtSite, updateSysXtSite } from "@/api/sysuser";
import { uploadFile } from "@/api/sysupload";

export function useRole() {
  const router = useRouter();

  const ruleFormRef = ref();
  const newFormInline = ref({
    id: "",
    name: "",
    site: "",
    api: "",
    operation1: "",
    operation2: ""
  });

  const multiTags = computed(() => {
    return useMultiTagsStoreHook()?.multiTags;
  });

  function closePageTag() {
    useMultiTagsStoreHook().handleTags("splice", "/system/site/index");
    router.push({
      path: multiTags.value[(multiTags as any).value.length - 1].path
    });
  }

  async function onSearch() {
    getSysXtSite()
      .then(res => {
        if (res.success) {
          newFormInline.value = res.data;
        } else {
          message("获取数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("获取数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(valid => {
      if (valid) {
        updateSysXtSite(newFormInline.value)
          .then(res => {
            if (res.success) {
              message("保存成功", { type: "success" });
            } else {
              message("保存失败:" + res.errMsg, { type: "error" });
            }
          })
          .catch(error => {
            message("保存失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    });
  };

  const fileList1 = ref([]);
  const fileList2 = ref([]);

  //监控数据变化，动态处理上传文件地址
  watch(newFormInline, () => {
    if (newFormInline.value.operation1) {
      const filename = newFormInline.value.operation1.substring(
        newFormInline.value.operation1.lastIndexOf("/") + 1
      );
      fileList1.value = [
        { name: filename, url: newFormInline.value.operation1 }
      ];
    } else {
      fileList1.value = [];
    }
    /////
    if (newFormInline.value.operation2) {
      const filename = newFormInline.value.operation2.substring(
        newFormInline.value.operation2.lastIndexOf("/") + 1
      );
      fileList2.value = [
        { name: filename, url: newFormInline.value.operation2 }
      ];
    } else {
      fileList2.value = [];
    }
  });

  //
  const beforeUpload1 = async file => {
    const form = new FormData();
    form.append("file", file);
    uploadFile(form)
      .then(res => {
        console.log(JSON.stringify(res));
        if (res.errno == 0) {
          message("上传成功", { type: "success" });
          fileList1.value = [
            {
              name: res.data.url.substring(res.data.url.lastIndexOf("/") + 1),
              url: res.data.url
            }
          ];
          newFormInline.value.operation1 = res.data.url;
          return false;
        } else {
          message("上传失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        console.log(JSON.stringify(error));
        message("上传失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  };

  const beforeRemove1 = () => {
    fileList1.value = [];
    newFormInline.value.operation1 = "";
    return false;
  };

  ///
  const beforeUpload2 = async file => {
    const form = new FormData();
    form.append("file", file);
    uploadFile(form)
      .then(res => {
        if (res.errno == 0) {
          message("上传成功", { type: "success" });
          console.log(JSON.stringify(res));
          fileList2.value = [
            {
              name: res.data.url.substring(res.data.url.lastIndexOf("/") + 1),
              url: res.data.url
            }
          ];
          newFormInline.value.operation2 = res.data.url;
          return false;
        } else {
          message("上传失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("上传失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  };

  const beforeRemove2 = () => {
    fileList2.value = [];
    newFormInline.value.operation2 = "";
    return false;
  };

  onMounted(() => {
    onSearch();
  });

  return {
    closePageTag,
    ruleFormRef,
    newFormInline,
    submitForm,
    fileList1,
    fileList2,
    beforeUpload1,
    beforeUpload2,
    beforeRemove1,
    beforeRemove2
  };
}
